<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> <span>{{ getPlantationName() + '作物信息' }}</span>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" size="small" @click="handleAddCrop"
                        >新增作物
                        </el-button>
                    </el-col>
                </el-row>
                <el-row>
                    <el-table
                            ref="multipleTableRef"
                            :data="cropList"
                            style="width: 100%"
                            @selection-change="handleSelectionChange"
                            border
                    >
                        <el-table-column type="selection" width="55"/>
                        <el-table-column prop="cropName" label="作物名称" align="center" width="180">
                        </el-table-column>
                        <el-table-column prop="createTime" label="作物创建时间" align="center" width="180"/>
                        <el-table-column prop="cropType" label="作物类型" align="center" width="180">
                            <template v-slot="scope">
                                <span>{{ plantationType(scope.row.cropType) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="cropPic" label="作物图片" align="center" width="180">
                            <template #default="scope">
                                <el-image class="table-td-thumb" :src="scope.row.cropPic"
                                          :preview-src-list="[scope.row.cropPic]">
                                </el-image>
                            </template>
                        </el-table-column>
                        <el-table-column prop="cropIntroduce" label="基本介绍" align="center"/>
                        <el-table-column label="操作" align="center" width="300">
                            <template #default="scope">
                                <el-button type="text" icon="el-icon-plus"
                                           @click="handleAddAdverse(scope.row)">新增不良事件
                                </el-button>
                                <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">
                                    编辑
                                </el-button>
                                <el-button type="text" icon="el-icon-delete" class="red"
                                           @click="handleDelete(scope.$index, scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-row>
            </div>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                               :page-size="query.pageSize" :total="pageTotal"
                               @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <!-- 新增不良事件弹出框 -->
        <el-dialog :title="title" v-model="open" width="30%" append-to-body>
            <el-form label-width="70px" ref="form" :model="form" :rules="rules">
                <el-form-item label="不良事件名称" prop="adverseName">
                    <el-input v-model="form.adverseName"></el-input>
                </el-form-item>
                <el-form-item label="不良事件类别" prop="adverseType">
                    <el-input v-model="form.adverseType"></el-input>
                </el-form-item>
                <el-form-item label="不良事件时间" prop="createTime">
                    <el-date-picker type="date" placeholder="选择日期" v-model="form.createTime"
                                    style="width: 100%;"></el-date-picker>
                </el-form-item>
                <el-form-item label="不良事件介绍" prop="adverseIntroduce">
                    <el-input v-model="form.adverseIntroduce" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="open = false">取 消</el-button>
                    <el-button type="primary" @click="commitAdverse()">提 交</el-button>
                </span>
            </template>
        </el-dialog>
        <!-- 新增作物弹出框 -->
        <el-dialog :title="title" v-model="openCrop" width="30%" append-to-body>
            <el-form label-width="70px" ref="formCrop" :model="formCrop" :rules="rulesCrop">
                <el-form-item label="作物名称" prop="cropName">
                    <el-input v-model="formCrop.cropName"></el-input>
                </el-form-item>
                <el-form-item label="作物类别" prop="adverseName">
                    <el-radio-group v-model="formCrop.cropType">
                        <el-radio-button label="0">植物</el-radio-button>
                        <el-radio-button label="1">动物</el-radio-button>
                    </el-radio-group>
                    <!--                    <el-radio-button v-model="formCrop.cropType" label="0" size="large">植物</el-radio-button>-->
                    <!--                    <el-radio-button v-model="formCrop.cropType" label="1" size="large">动物</el-radio-button>-->
                    <!--                    <el-input v-model=""></el-input>-->
                </el-form-item>
                <el-form-item label="作物简介" prop="cropName">
                    <el-input type="textarea" v-model="formCrop.cropIntroduce"></el-input>
                </el-form-item>
                <el-form-item label="作物照片" prop="adverseName">
                    <el-upload
                        class="avatar-uploader"
                        action="http://localhost:8001/AgriculturalBigData/upload/img"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl!=''" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon">上传图片</i>
                </el-upload>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="openCrop = false">取 消</el-button>
                    <el-button type="primary" @click="submitCrop">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import {ref, reactive} from "vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    import {getCropList, addCropAdverse,addCrop,editCrop} from "../api/index.js";
    import {useRouter, useRoute} from "vue-router";

    export default {
        name: "crop",
        components: {},
        data() {
            return {
                imageUrl: '',
                title: '',
                userId:'',
                cropList: [],
                plantationName: '',
                plantationId: '',
                cropId: '',
                open: false,
                openCrop: false,
                form: {
                    // cropId: '',
                    // cropName: '',
                    // cropIntroduce: '',
                    // growth: 0,
                    // temp: 0,
                    // humidity: 0,
                    // n: 0,
                    // p: 0,
                    // k: 0,
                    // light: 0,
                    // ph: 0,
                    // sort: 0,
                    // wind: 0,
                    // cropType: '',
                    // cropPic: '',
                    // createTime: '',
                    // createBy: '',
                    // plantationId: '',
                    // plantationName: '',
                    // // 盘点作业表
                    // userId: '',
                },
                rules: {},
                formCrop: {},
                rulesCrop: {
                    // cropName: [{
                    //     required: true,
                    //     message: "作物名称不能为空",
                    //     trigger: "blur"
                    // }],
                    // cropType: [{
                    //     required: true,
                    //     message: "作物类型不能为空",
                    //     trigger: "blur"
                    // }],
                    // cropPic: [{
                    //     required: true,
                    //     message: "照片不能为空",
                    //     trigger: "blur"
                    // }],
                },
            }
        },
        created() {
            const route = useRoute();
            // this.name = localStorage.getItem("ms_username");
            let plantationId = route.query.plantationId;
            this.plantationId = plantationId;
            this.userId = localStorage.getItem("user_id");
            console.log(plantationId);
            this.getList();
        },
        methods: {
            // 表单重置
            reset() {
                this.formCrop = {
                    cropId: null,
                    cropName: null,
                    cropIntroduce: null,
                    growth: null,
                    temp: null,
                    humidity: null,
                    n: "0",
                    p: null,
                    k: null,
                    light: null,
                    ph: null,
                    sort: null,
                    wind: null,
                    cropType: null,
                    cropPic: null,
                    createTime: null,
                    createBy: null,
                    plantationId: null,
                    plantationName: null,
                    // 盘点作业表
                    userId: null,
                };
                // this.resetForm("formCrop");
            },
            getList(){
                // 通过id获取用户所有信息
                getCropList({
                    plantationId: this.plantationId,
                    userId: this.userId
                }).then(res => {
                    this.cropList = res.rows;
                    this.plantationName = res.rows[0].plantationName;
                    // console.log("dasdhasdjhasdkjhas"+this.plantationName);
                });
            },
            // 种植园类型转换
            plantationType(status) {
                if (status == 0) {
                    return "植物"
                } else if (status == 1) {
                    return "动物"
                }
            },
            handleSelectionChange() {
            },
            handleEdit(row) {
                this.reset();

                this.openCrop = true;
                this.formCrop = row;
                this.title = "修改作物信息";
            },
            handleDelete(index) {
                // 二次确认删除
                ElMessageBox.confirm("确定要删除吗？", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        ElMessage.success("删除成功");
                        this.cropList.splice(index, 1);
                    })
                    .catch(() => {
                    });
            },
            handleAddCrop() {
                this.reset();
                this.openCrop = true;
                this.title = "添加作物信息";
            },
            handleAddAdverse(row) {
                this.cropId = row.cropId;
                this.form.cropName = row.cropName;
                console.log("dasdsda");
                this.open = true;
                this.title = "添加不良事件";
            },
            //图片回显
            handleAvatarSuccess(res, file) {
                // console.log(res)
                this.imageUrl = res.msg;
                // sessionStorage.setItem("imgUrl",this.imageUrl)
                // alert(this.imageUrl)
            },
            //图片上传大小限制
            beforeAvatarUpload(file) {
                const isLt2M = file.size / 1024 / 1024 < 2;
                if (!isLt2M) {
                    ElMessage.error('上传头像图片大小不能超过 2MB!');
                }
                return isLt2M;
            },
            // 跳转至当前园区的经济作物列表
            // forward(plantationId){
            //     console.log("????");
            //     router.push({
            //         path: '/crop',
            //         query: {
            //             plantationId:plantationId
            //         }
            //     })
            // }
            // 获取园区名称
            getPlantationName() {
                // console.log(this.plantationName)
                return this.plantationName;
            },
            // 提交作物表单
            submitCrop() {
                // this.$refs["formCrop"].validate(valid => {
                //     if (valid) {
                        if (this.formCrop.cropId != null) {
                            this.formCrop.cropPic = this.imageUrl;
                            this.formCrop.plantationId = this.plantationId;
                            this.formCrop.plantationName = this.plantationName;
                            this.formCrop.userId = this.userId;
                            editCrop(this.formCrop).then(response => {
                                ElMessage.success("修改成功");
                                this.openCrop = false;
                                this.getList();
                            }).catch((err) => {
                                // this.loading = false
                                console.log(err);
                            });
                        } else {
                            this.formCrop.cropPic = this.imageUrl;
                            this.formCrop.plantationId = this.plantationId;
                            this.formCrop.plantationName = this.plantationName;
                            this.formCrop.userId = this.userId;
                            console.log("------------表单内容------------");
                            console.log(this.formCrop);
                            addCrop(this.formCrop).then(response => {
                                ElMessage.success("新增成功");
                                this.openCrop = false;
                                this.getList();
                            }).catch((err) => {
                                // this.loading = false
                                console.log(err);
                            });
                        }
                //     }
                // });
            },
            commitAdverse() {
                // this.$refs["form"].validate(valid => {
                //     if (valid) {
                console.log("------------表单内容------------");
                console.log(this.form);
                this.form.userId = this.userId;
                this.form.plantationId = this.plantationId;
                this.form.cropId = this.cropId;
                addCropAdverse(this.form).then(response => {
                    this.msgSuccess("新增成功");
                    this.open = false;
                }).catch((err) => {
                    console.log(err);
                });
            }
            //     });
            // }
        },
        setup() {
            const query = reactive({
                address: "",
                name: "",
                pageIndex: 1,
                pageSize: 10,
            });
            const tableData = ref([]);
            const pageTotal = ref(0);
            // 获取表格数据
            const getData = () => {
                // fetchData(query).then((res) => {
                //     tableData.value = res.list;
                //     pageTotal.value = res.pageTotal || 50;
                // });
            };
            getData();

            // 查询操作
            const handleSearch = () => {
                query.pageIndex = 1;
                getData();
            };
            // 分页导航
            const handlePageChange = (val) => {
                query.pageIndex = val;
                getData();
            };

            // // 删除操作
            // const handleDelete = (index) => {
            //     // 二次确认删除
            //     ElMessageBox.confirm("确定要删除吗？", "提示", {
            //         type: "warning",
            //     })
            //         .then(() => {
            //             ElMessage.success("删除成功");
            //             tableData.value.splice(index, 1);
            //         })
            //         .catch(() => {
            //         });
            // };

            // // 表格编辑时弹窗和保存
            // const editVisible = ref(false);
            // let form = reactive({
            //     name: "",
            //     address: "",
            // });
            // let idx = -1;
            // const handleEdit = (index, row) => {
            //     idx = index;
            //     Object.keys(form).forEach((item) => {
            //         form[item] = row[item];
            //     });
            //     editVisible.value = true;
            // };
            // const saveEdit = () => {
            //     editVisible.value = false;
            //     ElMessage.success(`修改第 ${idx + 1} 行成功`);
            //     Object.keys(form).forEach((item) => {
            //         tableData.value[idx][item] = form[item];
            //     });
            // };
            const router = useRouter();
            const forward = () => {
                router.push({
                    path: '/crop',
                    query: {}
                })
            }
            return {
                query,
                tableData,
                pageTotal,
                // editVisible,
                // form,
                handleSearch,
                handlePageChange,
                // handleDelete,
                // handleEdit,
                forward,
                // saveEdit,
            };
        },
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }
</style>